﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Collections;
using TextMining.Models;
using TextMining.Helper;

namespace TextMining.Service
{
    public class FileService
    {
        public int NumOfCate = 0;
        public int HightMatrix = 3;
        public int[,] TrainingSet;
        public ArrayList ArrCate;   // Save catergory without calculate vertor
        public List<string> ListCate;  //Science, Education, Economic
        public ArrayList ArrVectorCate;   // Store vector of each Category
        public ArrayList ArrPC;
        public ArrayList ArrPCD;
        public MyDoc myDoc;
        public ArrayList ArrWordCate;

        public FileService()
        {
            ArrCate = new ArrayList();
            ListCate = new List<string>();
            ArrVectorCate = new ArrayList();
            ArrPC = new ArrayList();
            ArrPCD = new ArrayList();
            myDoc = new MyDoc();
            ArrWordCate = new ArrayList();
        }

        public void InitialSource(MyDoc cDoc)
        {
            myDoc = cDoc;
            foreach (var item in CharRemove.ListRemove)
            {
                myDoc.FullContent = myDoc.FullContent.Replace(item, " ").ToLower();
            }
            string[] words = myDoc.FullContent.Split(new Char[] { ' ', ',', '.', ':', '\t' });
            if (words.Length > 0)
            {
                for (int i = 0; i < words.Length; i++)
                {
                    if (!myDoc.Source.ContainsKey(words[i]))
                        myDoc.Source.Add(words[i], CodeHepler.CountWordInDoc(words[i], myDoc.FullContent) + 1);

                }
            }
            myDoc.ErrorStr = string.Empty;
        }


        public void GetTrainingSet()
        {

            string sFolder = HttpContext.Current.Server.MapPath("\\Category\\");
            DirectoryInfo di = new DirectoryInfo(sFolder);
            FileInfo[] aFileInfos = di.GetFiles("*.txt");

            NumOfCate = aFileInfos.Length;

            foreach (var item in aFileInfos)
            {
                try
                {
                    double dWeight = 0;

                    ListCate.Add(item.Name.Substring(0, item.Name.IndexOf('.') ));
                    Dictionary<string, int> dicCategory = new Dictionary<string, int>();

                    using (StreamReader sr = new StreamReader(item.FullName))
                    {
                        string sContent = sr.ReadToEnd();
                        ArrWordCate.Add(sContent.Split(new Char[] {',','\t' }));
                        if (!string.IsNullOrEmpty(sContent) && sContent != "")
                        {
                            //string[] arrItem = sContent.Split(new Char[] {' ', ',', '.', ':', '\t'});
                            //ListCate.Add(sContent);
                            string[] arrItem = myDoc.FullContent.Split(new Char[] { ' ', ',', '.', ':', '\t' });

                            int iCountWord = 0;
                            foreach (var word in arrItem)
                            {

                                if (!string.IsNullOrEmpty(word))
                                {
                                    //iCountWord = CodeHepler.CountWordInDoc(word, myDoc.FullContent) + 1;

                                    if (dicCategory.ContainsKey(word) == false)
                                    {
                                        if (sContent.ToLower().IndexOf(word)>=0)
                                            dicCategory.Add(word, myDoc.Source[word]);
                                        else
                                            dicCategory.Add(word, 1);
                                    }
                                }                               
                            }                            
                        }                       
                        ArrCate.Add(dicCategory);
                    }
                   
                }
                catch (Exception ex)
                {

                }
            }
           

        }

        public void CalculateVector()
        {
            if (ArrCate.Count > 0)
            {

                foreach (var arrCate in ArrCate)
                {
                    Dictionary<string, double> dicVectorCal = new Dictionary<string, double>();
                    foreach (KeyValuePair<string, int> cate in arrCate as System.Collections.IEnumerable)
                    {
                        if (dicVectorCal.ContainsKey(cate.Key) == false)
                        dicVectorCal.Add(cate.Key, CalVector(double.Parse(cate.Value.ToString())));
                    }
                    ArrVectorCate.Add(dicVectorCal);
                }
            }
        }

        public double CalVector(double iCurrentVal)
        {
            double dResult = 0;   

            if (iCurrentVal > 1)
                dResult = iCurrentVal / (1 + NumOfCate);
            else
                dResult = iCurrentVal / (NumOfCate);


            return dResult;
        }

        public void CalPC()
        {
            if (ArrCate.Count > 0)
            {
                double dTotal = 0;

                foreach (Dictionary<string, int> arrCate in ArrCate)
                {
                    foreach (KeyValuePair<string, int> cate in arrCate as System.Collections.IEnumerable)
                    {
                        if (cate.Value > 1)
                            dTotal += cate.Value;
                    }
                }

                foreach (Dictionary<string, int> arrCate in ArrCate)
                {
                    Dictionary<string, double> dicPC = new Dictionary<string, double>();
                    double dSumWeight = 0;
                    
                    foreach (KeyValuePair<string, int> cate in arrCate as System.Collections.IEnumerable)
                    {
                        if (cate.Value > 1)
                            dSumWeight += cate.Value;                                                
                    }

                    ArrPC.Add((1 + dSumWeight) / (myDoc.Source.Count + dTotal));  // Store PC for each category
                }
            }
        }

        public string CalPC_over_Doc()
        {
            string sCategory = string.Empty;
            double dMax = 0;
            int index = 0;
            double dmin = 0;
            int imin = 0;
            if (ArrCate.Count > 0)
            {
                int iIndexCate = 0;
                foreach (var arrVectorCate in ArrVectorCate)
                {
                    double dWeightCate = 1;
                    foreach (KeyValuePair<string, double> word in arrVectorCate as System.Collections.IEnumerable)
                    {
                        dWeightCate *= word.Value;
                    }

                    Dictionary<string, double> dicPCD = new Dictionary<string, double>();

                    double dPCD = double.Parse((dWeightCate * double.Parse(ArrPC[iIndexCate].ToString())).ToString());
                    
                    

                    if (dicPCD.ContainsKey(ListCate[iIndexCate]) == false)
                        dicPCD.Add(ListCate[iIndexCate], dPCD);
                    if (dWeightCate * Convert.ToDouble(ArrPC[iIndexCate]) > dMax)
                    {
                        dMax = dWeightCate * Convert.ToDouble(ArrPC[iIndexCate]);
                        index = iIndexCate;
                    }
                    else
                    {
                        dmin = dWeightCate * Convert.ToDouble(ArrPC[iIndexCate]);
                        imin = iIndexCate;
                    }

                    ArrPCD.Add(dicPCD);

                    iIndexCate++;
                }
            }
            sCategory = ListCate[index].ToString();
            return sCategory+"|"+index;
        }

    }
}